<template>
  <div class="flex flex-col h-full">
    <el-form :inline="true" :model="selectProps" class="demo-form-inline">
      <el-form-item>
        <el-input v-model="selectProps.title" placeholder="请输入标题" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSelect">搜索</el-button>
        <el-button type="danger" @click="deleteInfos">删除</el-button>
      </el-form-item>
    </el-form>
    <el-table class="flex-1 " :data="tableData" stripe style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" :fixed="true" />
      <el-table-column type="index" label="序号" width="80" :fixed="true" align="center" :index="TableIndexMethod" />
      <el-table-column prop="title" label="文件标题" align="center" show-overflow-tooltip />
      <el-table-column prop="remark" label="描述" align="center" show-overflow-tooltip />
      <el-table-column prop="userId" label="上传者" align="center">
        <template #default="scope">
          <span>
            {{ userData.find((item) => item.id == scope.row.userId) ? userData.find((item) => item.id ==
              scope.row.userId).username : "" }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="createDate" label="上传时间" align="center" />
      <el-table-column label="操作" align="center" width="200">
        <template #default="scope">
          <el-button type="info" size="small" @click="getInfo(scope)">编辑</el-button>
          <el-button type="primary" size="small" @click="downloadFile(scope)">下载</el-button>
          <el-button type="danger" size="small" @click="deleteInfo([scope.row.id])">删除</el-button>
        </template>
      </el-table-column>

    </el-table>
    <el-pagination class="mt-2" v-model:current-page="tableProps.currentPage" v-model:page-size="tableProps.pageSize"
      :page-sizes="[15, 30]" layout="total, sizes, prev, pager, next, jumper" :total="tableProps.total"
      @size-change="handleSizeChange" @current-change="handleCurrentChange" />
  </div>
  <el-dialog v-model="infoVisible" title="信息修改" width="550">
    <el-form ref="formRef" :inline="true" :model="info" :rules="rules">
      <el-form-item prop="title" label="文件标题：" class="w-full ">
        <el-input v-model="info.title" clearable />
      </el-form-item>
      <el-form-item prop="remark" label="文件描述：" class="w-full ">
        <el-input v-model="info.remark" clearable type="textarea" :autosize="{ minRows: 5 }" />
      </el-form-item>
      <el-form-item label="文件：">
        <el-upload ref="uploadRef" class="upload-demo" action="/admin/documentInf/upload" :limit="1"
          :on-exceed="handleExceed" :on-change="handleChange" :auto-upload="false" :headers="uploadHeaders"
          v-model:file-list="uploadList">
          <template #trigger>
            <el-button type="primary">上传文件</el-button>
          </template>
        </el-upload>
      </el-form-item>
      <div>
        <el-form-item label="上传者：">
          <el-input v-model="info.username" disabled />
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="infoVisible = false">取消</el-button>
        <el-button type="primary" @click="handleInfoChange(formRef)">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ApiDelete, ApiGet, ApiPost, ApiPut } from '@/utils/Axios';
import axios from 'axios';
import { ElMessageBox, ElNotification, genFileId, UploadInstance, UploadProps, UploadRawFile, type FormInstance } from 'element-plus';
import { onBeforeMount, reactive, ref, watch } from 'vue'
const tableProps = ref({
  currentPage: 1,
  pageSize: 15,
  total: 30,
})
const selectProps = reactive({
  title: "",
})
const tableData = ref([])
const userData = ref([])
const multipleSelection = ref([])
const info = ref({
  id: null,
  title: "",
  remark: "",
  filename: null,
  username: null,
  token: null
})
const infoVisible = ref(false)
const formRef = ref<FormInstance>()
const uploadRef = ref<UploadInstance>()
const uploadHeaders = {
  "Authorization": localStorage.getItem("token"),
}
const uploadList = ref([])

onBeforeMount(() => {
  getTableData(tableProps.value.currentPage, tableProps.value.pageSize)
  getUserData();
  info.value.token = window.localStorage.getItem("token")
})

watch(tableProps, (newVal, oldVal) => {
  getTableData(newVal.currentPage, newVal.pageSize)
})

const TableIndexMethod = (index: number) => {
  return (tableProps.value.currentPage - 1) * tableProps.value.pageSize + index + 1
}

const getTableData = (currentPage, pageSize) => {
  ApiPost("/documentInf/page", {
    page: Number(currentPage),
    pageSize: Number(pageSize),
    ...selectProps,
  }).then(res => {
    console.log(res)
    if (res.code === 200) {
      tableData.value = res.data.records
      tableProps.value.total = res.data.total
    } else {
      console.log("错误=>", res.msg);
    }
  }).catch(err => {
    console.log("错误=>", err);
  })
}

const getUserData = () => {
  ApiPost("/userInf/page", {
    page: 1,
    pageSize: 1000,
  }).then(res => {
    if (res.code === 200) {
      userData.value = res.data.records
    } else {
      console.log("错误=>", res.msg);
    }
  }).catch(err => {
    console.log("错误=>", err);
  })
}

const onSelect = () => {
  tableProps.value.currentPage = 1
  getTableData(tableProps.value.currentPage, tableProps.value.pageSize)
}

const deleteInfo = (noticeList: number[]) => {
  ElMessageBox({
    title: "警告",
    type: "warning",
    message: "确认删除该上传信息吗？",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    showCancelButton: true,
  }).then(() => {
    ApiDelete("/documentInf/delete", { ids: noticeList.join(",") }).then(res => {
      if (res.code === 200) {
        getTableData(tableProps.value.currentPage, tableProps.value.pageSize)
        ElNotification({
          title: "删除成功",
          type: "success",
          showClose: false,
          duration: 2000,
        })
      } else {
        ElNotification({
          title: "删除失败",
          type: "error",
          message: res.msg,
          showClose: false,
          duration: 2000,
        })
      }
    }).catch((err) => {
      console.log("删除失败")
    })
  }).catch(() => {
    return
  })
}

const deleteInfos = () => {
  if (multipleSelection.value.length === 0) {
    return
  }
  const depList = multipleSelection.value.map(item => item.id)
  deleteInfo(depList)
}

const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const getInfo = (scope) => {
  info.value = { ...scope.row, username: userData.value.find((item) => item.id == scope.row.userId)?.username }
  uploadList.value = [{
    name: scope.row.filename,
  }]
  infoVisible.value = true
}

const downloadFile = (scope) => {
  axios({
    url: "/admin/documentInf/download/" + scope.row.filename,
    method: "get",
    responseType: "blob",
    headers: {
      "Authorization": window.localStorage.getItem("token")
    }
  }).then((res) => {
    console.log("test=>", res)
     // 创建一个 URL 对象，用于创建下载链接
     const url = window.URL.createObjectURL(new Blob([res.data]));
        // 创建一个 a 标签，设置其 href 和 download 属性
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', scope.row.filename);
        // 将 a 标签添加到文档中，并模拟点击事件
        document.body.appendChild(link);
        link.click();
        // 下载完成后，移除 a 标签
        link.parentNode.removeChild(link);
    
  }).catch((err) => {
    console.log("下载失败")
  })
}

const validateFiletitle = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('文件标题不能为空'))
  } else {
    callback()
  }
}

const validateFileremark = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('文件描述不能为空'))
  } else {
    callback()
  }
}
const rules = reactive({
  title: [{ validator: validateFiletitle, trigger: 'blur' }],
  remark: [{ validator: validateFileremark, trigger: 'blur' }],
})

const handleInfoChange = (formEl: FormInstance | undefined) => {
  formEl.validate(vail => {
    if (vail && info.value.id) {
      ElMessageBox({
        title: "提醒",
        type: "warning",
        message: "确认修改文件相关信息吗？",
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        showCancelButton: true,
      }).then(() => {
        const { id, title, remark, filename } = info.value
        ApiPut("/documentInf/update", { id, title, remark, filename }).then(res => {
          console.log(res)
          if (res.code === 200) {
            infoVisible.value = false
            getTableData(tableProps.value.currentPage, tableProps.value.pageSize)
            ElNotification({
              title: "修改成功",
              type: "success",
              showClose: false,
              duration: 2000,
            })
          }
        })
      }).catch(() => {
        return
      })
    }
  })

}

const handleExceed: UploadProps['onExceed'] = (files) => {
  uploadRef.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  uploadRef.value!.handleStart(file)
}

const handleChange: UploadProps['onChange'] = (file, fileList) => {
  switch (file.status) {
    case "ready":
      uploadRef.value!.submit()
      break;
    case "uploading":
      break;
    case "success":
      if (file.response["code"] === 200) {
        info.value.filename = file.response["data"].fileName
      }
      break;
    default:
      break;
  }
}

const handleSizeChange = (val) => {
  tableProps.value = { ...tableProps.value, pageSize: val };
};
const handleCurrentChange = (val) => {
  tableProps.value = { ...tableProps.value, currentPage: val };
};
</script>